package com.hemerasolutions.v2trainer.util.primefaces;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import org.primefaces.component.api.UIColumn;
import org.primefaces.component.datatable.DataTable;
import org.primefaces.component.datatable.DataTableRenderer;
import org.primefaces.component.subtable.SubTable;

public class CustomTableRenderer extends DataTableRenderer {


@Override
	protected void encodeCell(FacesContext context, DataTable table, UIColumn column, String clientId, boolean selected) throws IOException {
        if(!column.isRendered()) {
            return;
        }
        
        ResponseWriter writer = context.getResponseWriter();
        boolean selectionEnabled = column.getSelectionMode() != null;
        String style = column.getStyle();
        String styleClass = selectionEnabled ? DataTable.SELECTION_COLUMN_CLASS : (column.getCellEditor() != null) ? DataTable.EDITABLE_COLUMN_CLASS : null;
        String userStyleClass = column.getStyleClass();
        styleClass = userStyleClass == null ? styleClass : (styleClass == null) ? userStyleClass : styleClass + " " + userStyleClass;
        
        writer.startElement("td", null);
        writer.writeAttribute("role", "gridcell", null);

//Begin custom
        if(column.getColspan() != 1) writer.writeAttribute("colspan", column.getColspan(), null);
        if(column.getRowspan() != 1) writer.writeAttribute("rowspan", column.getRowspan(), null);
//End custom        
        
        if(style != null) writer.writeAttribute("style", style, null);
        if(styleClass != null) writer.writeAttribute("class", styleClass, null);

        if(selectionEnabled)
            encodeColumnSelection(context, table, clientId, column, selected);
        else
            column.encodeAll(context);            

        writer.endElement("td");
    }
	
@Override
public void encodeTbody(FacesContext context, DataTable table, boolean dataOnly) throws IOException {

    
	@SuppressWarnings("rawtypes")
	Class noparams[] = {};
	
	ResponseWriter writer = context.getResponseWriter();
    String rowIndexVar = table.getRowIndexVar();
    String clientId = table.getClientId(context);
    String emptyMessage = table.getEmptyMessage();
    UIComponent emptyFacet = table.getFacet("emptyMessage");
    SubTable subTable = table.getSubTable();
            
    if(table.isSelectionEnabled()) {
    	
// Invoke by reflection.....C'mon, why isn't public? !!!!    	
    	try {
			Method m = table.getClass().getDeclaredMethod("findSelectedRowKeys", noparams);
			m.setAccessible(true);
			m.invoke(table);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
    	//        table.findSelectedRowKeys();
    }

    int rows = table.getRows();
	int first = table.getFirst();
    int rowCount = table.getRowCount();
    int rowCountToRender = rows == 0 ? (table.isLiveScroll() ? table.getScrollRows() : rowCount) : rows;
    boolean hasData = rowCount > 0;
          
    if(!dataOnly) {
        writer.startElement("tbody", null);
        writer.writeAttribute("id", clientId + "_data", null);
        writer.writeAttribute("class", DataTable.DATA_CLASS, null);
    }

    if(hasData) {
        if(subTable != null)
            encodeSubTable(context, table, subTable, first, (first + rowCountToRender));
        else
            encodeRows(context, table, first, (first + rowCountToRender));
    }
    else {
        //Empty message
        writer.startElement("tr", null);
        writer.writeAttribute("class", DataTable.EMPTY_MESSAGE_ROW_CLASS, null);

        writer.startElement("td", null);

        // Begin
        //        writer.writeAttribute("colspan", table.getColumnsCount(), null);
        int colspan = 0;	
        for( UIColumn column: table.getColumns()){
        	colspan = colspan + column.getColspan();
        }
        if(colspan == 0)
        	writer.writeAttribute("colspan", table.getColumnsCount(), null);
        else
        	writer.writeAttribute("colspan", colspan, null);
        // End        
        
        
        if(emptyFacet != null)
            emptyFacet.encodeAll(context);
        else
            writer.write(emptyMessage);

        writer.endElement("td");
        
        writer.endElement("tr");
    }
	
    if(!dataOnly) {
        writer.endElement("tbody");
    }

	//Cleanup
	table.setRowIndex(-1);
	if(rowIndexVar != null) {
		context.getExternalContext().getRequestMap().remove(rowIndexVar);
	}
}



}
